import axios from 'axios'
import {ElMessage} from "element-plus";


const defaultError = (error) => {
    let errorMessage = error || '发生未知错误';
    console.warn(errorMessage);
    ElMessage.warning('发生未知错误，请将控制台打印的错误反馈给管理员！')
}

const defaultFailure = (message, code, url) => {
    console.warn(`请求地址:${url},状态码:${code},错误信息:${message}`)
    ElMessage.warning(message)
}


const internalGet = (url, headers, success, failure, error = defaultError) => {
    axios.get(url, {headers: headers}).then(response => {
        const data = response.data;
        if (data.code === 200) {
            success(data);
        } else {
            failure(data.message, data.code, url);
        }
    }).catch(error => error(error));
}

const internalPost = (url, data, headers, success, failure, error = defaultError) => {
    axios.post(url, data, {headers: headers}).then(response => {
        const data = response.data;
        if (data.code === 200) {
            success(data);
        } else {
            failure(data.message, data.code, url);
        }
    }).catch(error => error(error));
}

const storeAccessToken = (token, remember, expire) => {
        const auth = {
            'expire': expire,
            'token': token
        }
        const authStr = JSON.stringify(auth);
        remember ? localStorage.setItem('access_token', authStr) : sessionStorage.setItem('access_token', authStr);
}
const deleteAccessToken = () => {
    localStorage.removeItem('access_token');
    sessionStorage.removeItem('access_token');
}
const takeAccessToken = () => {
    const token = localStorage.getItem('access_token') || sessionStorage.getItem('access_token');
    if (!token) return null;
    const auth = JSON.parse(token)
    if (new Date(auth.expire) <= new Date()) {
        // JWT令牌过期
        deleteAccessToken();
        ElMessage.warning('登录已过期，请重新登录！');
        return null;
    }
    return auth.token;
}

export const accessHeader = () => {
    return takeAccessToken() ? {'authorization': `Bearer ${takeAccessToken()}`} : {};

}

const get = (url, success, failure = defaultFailure) => {
    internalGet(url, accessHeader(), success, failure)
}
const post = (url, data, success, failure = defaultFailure) => {
    internalPost(url, data, accessHeader(), success, failure)
}

const login = (username, password, remember, success, failure = defaultFailure) => {
    internalPost('/api/user/login', {
        username: username,
        password: password,
    }, {
        'Content-Type': 'application/json;charset=UTF-8',
    }, (response) => {
        const data = response.data;
        console.log(data)
        storeAccessToken(data.token, remember, data.expire);
        ElMessage.success(`登录成功，欢迎${data.username}来到本系统`)
        success(data)
    }, failure)
}

const logout = (success, failure = defaultFailure) => {
    get('/api/user/logout', () => {
        deleteAccessToken()
        ElMessage.success('退出成功')
        success()
    }, failure)
}

function unauthorized() {
    return !takeAccessToken()
}

export {login, logout, get, post, unauthorized}